$(function () {
    initLayerDate("#startDate",true);
    queryAjaxGiftCardList(1);
    $('body').on('click', '#submitFrom,#querySubmit', function () {
        //点击搜索查询从第一页开始查询
        queryAjaxGiftCardList(1);
    });
    selectUserCommon();
    //单个冻结,恢复
    $('body').on('click', '.unlockAndHistory', function () {
        var obj = $(this);
        var giftCardIds = $(this).data('id');
        var status = $(this).data('status');
        icModale(2, "确认要冻结所选礼品卡么？", 3, function () {
            if (status == 1) {
                updateStatusByGiftCardIds(giftCardIds, obj, 2);
            } else if (status == 2) {
                updateStatusByGiftCardIds(giftCardIds, obj, 1);
            }
        });
    });
    //单个上架
    $('body').on('click', '.releaseAndUnRelease', function () {
        var obj = $(this);
        var giftCardIds = $(this).data('id');
        icModale(2, "确认要发布所选礼品卡么？", 3, function () {
            updateStatusByGiftCardIds(giftCardIds, obj, 0);
        });
    });
    //删除礼品卡
    $('body').on('click', '.deleteGiftCard', function () {
        var obj = $(this);
        var giftCardIds = $(this).data('id');
        icModale(2, "确认要删除所选礼品卡么？", 3, function () {
            updateStatusByGiftCardIds(giftCardIds, obj, 3);
        });
    });
    //批量删除
    $('body').on('click', '#deleteBatch', function () {
        var obj = $("input[name='giftCardId']:checked");
        var giftCardIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(giftCardIds)) {
            icModale(2, "确认要删除所选礼品卡么？", 3, function () {
                updateStatusByGiftCardIds(giftCardIds, obj, 3);
            });
        }
    });
    //批量恢复
    $('body').on('click', '#historyBatch', function () {
        var obj = $("input[name='giftCardId']:checked");
        var giftCardIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(giftCardIds)) {
            icModale(2, "确认要恢复所选礼品卡么？", 3, function () {
                updateStatusByGiftCardIds(giftCardIds, obj, 1);
            });
        }
    });
    //批量冻结
    $("body").on("click", "#unlockBatch", function () {
        var obj = $("input[name='giftCardId']:checked");
        var giftCardIds = obtainIds(obj);//获取勾选ids
        if (!$.isEmptyObject(giftCardIds)) {
            icModale(2, "确认要冻结所选礼品卡么？", 3, function () {
                updateStatusByGiftCardIds(giftCardIds, obj, 2);
            });
        }
    });

    //判断勾选ID是否为空
    function obtainIds(obj) {
        if (obj.size() == 0) {
            icModale(0, "请选择要批量操作的数据");
            return null;
        } else {
            var giftCardIds = "";
            obj.each(function (index, em) {
                giftCardIds += em.value + ",";
            })
            giftCardIds = giftCardIds.substr(0, giftCardIds.length - 1);
            return giftCardIds;
        }
    }
});


/**
 * 批量封禁，批量恢复，批量删除
 * @param userIds
 * @param obj
 * @param isavalible
 */
function updateStatusByGiftCardIds(giftCardIds, obj, status) {
    var _status = "";
    if (status == 0) {
        status = 1;
        _status = 0;
    }
    $.ajax({
        url: baseloaction + "/admin/op/giftCard/updateOpGiftCardStatus",
        data: {"giftCardIds": giftCardIds, "status": status},
        type: "post",
        dataType: "json",
        success: function (result) {
            if (result.success) {
                if (2 == status) {
                    obj.parents('tr').find('.status').html('');
                    obj.parents('tr').find('.status').append('<span class="label label-danger">冻结</span>');
                    obj.parents('tr').find(".unlockAndHistory").html("");
                    obj.parents('tr').find(".unlockAndHistory").data('status', '2');
                    obj.parents('tr').find(".unlockAndHistory").append('<i class="fa fa-history"></i>')
                }
                if (0 == _status && status == 1) {
                    obj.attr('class', 'c-master fs14 ml5 unlockAndHistory');
                    obj.parents('tr').find('.status').html('');
                    obj.parents('tr').find('.status').append('<span class="label label-info">正常</span>');
                    obj.parents('tr').find(".unlockAndHistory")
                        .html('<i class="fa fa-unlock-alt"></i>')
                        .data('status', '1').attr('data-original-title', '冻结');
                }
                if (1 == status && _status != 0) {
                    obj.parents('tr').find('.status').html('');
                    obj.parents('tr').find('.status').append('<span class="label label-info">正常</span>');
                    obj.parents('tr').find(".unlockAndHistory").html("");
                    obj.parents('tr').find(".unlockAndHistory").data('status', '1');
                    obj.parents('tr').find(".unlockAndHistory").append('<i class="fa fa-unlock-alt"></i>')
                }
                if (3 == status) {
                    obj.parents('tr').html('');
                    var giftCardCount = $("#giftCardCount").val();
                    $("#totalNum").html('（共' + (giftCardCount - obj.size()) + '张优惠券）');
                    $("#giftCardCount").val((giftCardCount - obj.size()));
                    if ((giftCardCount - obj.size()) == 0) {
                        $("#tbodyGiftCard").append(
                            ' <td colspan="10" class="text-center">'
                            + '<div class="noDataTipsBox">'
                            + '<p><span class="c-4e fs16">亲，还没有数据~~~</span></p>'
                            + '</div>'
                            + '</td>'
                        );
                    }
                }
                icModale(0, result.message);
            } else {
                icModale(0, result.message);
            }
        },
        error: function (error) {
            icModale(0, "系统繁忙,请稍后重试");
        }
    })
}

/**
 * 查找用户赠送
 */
var dataId="";
function selectUserCommon() {
    $('body').on('click', '#selectUser', function () {
        selectUser("checkbox","");
        dataId = $(this).data('id');
    });
}

/**
 * 选择课程回调
 * @param result 回调数据
 */
function selectUserCallback(result) {
    if(result!=null && result.length>0){
        var userIds = "";
        $.each(result,function (index,user) {
            if(userIds.indexOf(","+user.id+",")==-1 && userIds.indexOf(user.id + ",") == -1){
                userIds +=user.id+","
            }
        });
        $.ajax({
            url: baseloaction + "/admin/op/giftCard/presentGiftCard",
            data: {"userIds": userIds, "giftCardId": dataId},
            dataType: "json",
            type: "post",
            success: function (result) {
                if(result.success){
                    icModale(0, result.message);
                    dataId="";
                    parent.layer.close(index);
                }else{
                    icModale(0, result.message);
                }
            }
        });
    }
}



/**
 * 获取角色列表页面
 * @param pageNo 当前页码
 */
function queryAjaxGiftCardList(pageNo) {
    var params = $("#search-form").serializeJSON();
    params = JSON.stringify(params);
    var obj = {
        url: baseloaction + '/admin/op/giftCard/queryGiftCardListPage',//请求URL
        contextId: 'giftCard-list-context',//响应内容页面设置内容ID
        params: params,//请求参数
        pageNo: pageNo,//页码
        pageCall: queryAjaxGiftCardList, //分页回调加载数据(点击上下页时调用,该方法也在加载页面完成时调用)
        selectAllId: 'select-all-giftCard', //全选框ID
        callback: function () {//数据加载完成回调
            $("#totalNum").html("（共"+total+"个礼品卡）");
            $("#couponCount").val(total);
        }
    };
    ajaxGetListData(obj)
}


